package com.oracle.lingshangejia.activity;

import android.annotation.SuppressLint;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.lws.basic.utils.common.AdapterIntegerDefault0;
import com.lws.basic.utils.common.DoubleDefault0Adapter;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.adapter.FileListAdapter;
import com.oracle.lingshangejia.base.BaseActivity;
import com.oracle.lingshangejia.bean.ResidentBean;
import com.oracle.lingshangejia.bean.User;
import com.oracle.lingshangejia.model.OkgoNetwork;
import com.oracle.lingshangejia.utils.MyLogger;
import com.oracle.lingshangejia.utils.MyToast;
import com.oracle.lingshangejia.utils.ObserverOnNext;
import com.oracle.lingshangejia.utils.OkHttpUtils;
import com.oracle.lingshangejia.utils.RxUtils;
import com.oracle.lingshangejia.utils.SpUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

public class SearchResidentActivity extends BaseActivity implements View.OnClickListener {
    private String key;
    private RecyclerView recyclerView;
    private FileListAdapter fileListAdapter;
    private TextView tv_title;
    private ImageButton ib_back;
    private int mOffset = 0;
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;
    private ResidentBean mBean;

    @Override
    public int intiLayout() {
        return R.layout.activity_searchresident;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
       key=getIntent().getStringExtra("key");
       recyclerView=findViewById(R.id.searchresident_recycle);
       tv_title=findViewById(R.id.tv_title);
       tv_title.setText("居民列表");
       ib_back=findViewById(R.id.ib_back);
       ib_back.setOnClickListener(this);
       LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
       linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
       recyclerView.setLayoutManager(linearLayoutManager);
        mSrl.setPrimaryColorsId(R.color.color_main);

    }

    private void initRefresh() {
        mSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getNetWork();
            }
        });
        mSrl.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                loadmore();
            }
        });
    }

    @Override
    public void initData() {
        getNetWork();
        initRefresh();
    }
    /**
     * 获取居民列表
     */
    private void getNetWork() {
        mOffset =0;
        int ysid= (int) SpUtils.get(SearchResidentActivity.this,"ysid",0);
        HashMap<Object,Object> map = new HashMap<>();
        map.put("ysid",ysid);
        map.put("mhcx",key);
        map.put("offset", mOffset);
        map.put("limit", 10);
        OkHttpUtils.getNetWork(this, Constant.baseurl+"online/user/getjmList",map,handler);
    }
    @SuppressLint("HandlerLeak")
    private android.os.Handler handler=new android.os.Handler(){
        @Override
        public void handleMessage(Message msg) {
            mSrl.finishRefresh();
            switch (msg.what){
                case 1:
                    try{
                        String s= (String) msg.obj;
                        Gson gson = new GsonBuilder()
                                .registerTypeAdapter(Integer.class, new AdapterIntegerDefault0())
                                .registerTypeAdapter(int.class, new AdapterIntegerDefault0())
                                .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                                .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                                .create();
                        mBean = gson.fromJson(s,ResidentBean.class);
                        if(mBean.getData()!= null&& mBean.getData().size()>0){
                            fileListAdapter=new FileListAdapter(SearchResidentActivity.this, mBean.getData());
                            //设置adapter
                            recyclerView.setAdapter(fileListAdapter);
                          /*  fileListAdapter.setLinsner(new FileListAdapter.OnRefreshLinsner() {
                                @Override
                                public void refresh() {
                                    getNetWork();
                                }
                            });
                            fileListAdapter.setOnItemClickListener(new FileListAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(View view, int postion) {

                                }
                            });*/
                        }else{
                            Toast.makeText(SearchResidentActivity.this, mBean.getMsg(),Toast.LENGTH_SHORT).show();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                case 2: //连接上服务器，错误
                    String error= (String) msg.obj;
                    Toast.makeText(SearchResidentActivity.this,error,Toast.LENGTH_SHORT).show();
                    break;
                case 3:  //没有网络
                    Toast.makeText(SearchResidentActivity.this,"网络不可用",Toast.LENGTH_SHORT).show();
                    break;
                case 4: //没有连接上服务器
                    Toast.makeText(SearchResidentActivity.this,"连接服务器失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void loadmore() {
        showLoading();
        mOffset += 10;
        Observable.create(new ObservableOnSubscribe<ResidentBean>() {
            @Override
            public void subscribe(ObservableEmitter<ResidentBean> emitter) throws Exception {
                int ysid= (int) SpUtils.get(SearchResidentActivity.this,"ysid",0);

                Map<Object, Object> map = new HashMap<>();
                map.put("token", User.getToken());
                map.put("mark", 1);
                map.put("offset", mOffset);
                map.put("limit", 10);
                map.put("ysid",ysid);
                map.put("mhcx",key);
                JSONObject jsonObject = new JSONObject(map);
                MyLogger.i(jsonObject.toString());
                Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Integer.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(int.class, new AdapterIntegerDefault0())
                        .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                        .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                        .create();
                String json = OkgoNetwork.post(Constant.baseurl+"online/user/getjmList", jsonObject.toString());
                MyLogger.i(json);
                emitter.onNext(gson.fromJson(json, ResidentBean.class));

            }
        }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<ResidentBean>() {
            @Override
            public void onNext(ResidentBean bean) {
                mSrl.finishLoadmore();
                if (bean.getData() !=null && bean.getData().size()>0){
                    mBean.getData().addAll(bean.getData());
                    fileListAdapter.loadmoreDate(bean.getData());
                }else {
                    MyToast.show("没用更多居民了");
                }
                mSrl.finishLoadmore();
                dismissLoading();
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ib_back:
                finish();
                break;
        }
    }
}
